package com.lyz.dataStructure.面试算法题.GrowingIO;

/**
 *@Author:759057893@qq.com Lyz
 *@Date: 2019/9/2 13:23
 *@Description:
 **/

/*
线程死锁
 */
public class DeadLock {

    public static String str1 = "str1";
    public static String str2 = "str2";
    public static void main(String[] args) {
        Thread t1 = new Thread(new Lock1());
        Thread t2 = new Thread(new Lock2());
        t1.start();
        t2.start();
    }
}

class  Lock1 implements Runnable{
    @Override
    public void run() {
        try {
            System.out.println("线程"+Thread.currentThread().getName()+"开始运行");
            while (true){
                synchronized (DeadLock.str1){
                    System.out.println("线程"+Thread.currentThread().getName()+"锁住str1");
                    Thread.sleep(3000);
                    synchronized (DeadLock.str2){
                        System.out.println("线程"+Thread.currentThread().getName()+"锁住str2");
                    }
                }
            }
        }catch (Exception e){
         e.printStackTrace();
        }
    }
}

class  Lock2 implements Runnable{
    @Override
    public void run() {
        try {
            System.out.println("线程"+Thread.currentThread().getName()+"开始运行");
            while (true){
                synchronized (DeadLock.str2){
                    System.out.println("线程"+Thread.currentThread().getName()+"锁住str2");
                    Thread.sleep(3000);
                    synchronized (DeadLock.str1){
                        System.out.println("线程"+Thread.currentThread().getName()+"锁住str1");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

